# LocalStack Resource Provider Scaffolding v2
from __future__ import annotations

import json
from pathlib import Path
from typing import Optional, TypedDict

import localstack.services.cloudformation.provider_utils as util
from localstack.services.cloudformation.resource_provider import (
    OperationStatus,
    ProgressEvent,
    ResourceProvider,
    ResourceRequest,
)


class ApiGatewayModelProperties(TypedDict):
    RestApiId: Optional[str]
    ContentType: Optional[str]
    Description: Optional[str]
    Name: Optional[str]
    Schema: Optional[dict | str]


REPEATED_INVOCATION = "repeated_invocation"


class ApiGatewayModelProvider(ResourceProvider[ApiGatewayModelProperties]):
    TYPE = "AWS::ApiGateway::Model"  # Autogenerated. Don't change
    SCHEMA = util.get_schema_path(Path(__file__))  # Autogenerated. Don't change

    def create(
        self,
        request: ResourceRequest[ApiGatewayModelProperties],
    ) -> ProgressEvent[ApiGatewayModelProperties]:
        """
        Create a new resource.

        Primary identifier fields:
          - /properties/RestApiId
          - /properties/Name

        Required properties:
          - RestApiId

        Create-only properties:
          - /properties/ContentType
          - /properties/Name
          - /properties/RestApiId



        IAM permissions required:
          - apigateway:POST
          - apigateway:GET

        """
        model = request.desired_state
        apigw = request.aws_client_factory.apigateway

        if not model.get("Name"):
            model["Name"] = util.generate_default_name(
                stack_name=request.stack_name, logical_resource_id=request.logical_resource_id
            )

        if not model.get("ContentType"):
            model["ContentType"] = "application/json"

        schema = json.dumps(model.get("Schema", {}))

        apigw.create_model(
            restApiId=model["RestApiId"],
            name=model["Name"],
            contentType=model["ContentType"],
            schema=schema,
        )

        return ProgressEvent(
            status=OperationStatus.SUCCESS,
            resource_model=model,
            custom_context=request.custom_context,
        )

    def read(
        self,
        request: ResourceRequest[ApiGatewayModelProperties],
    ) -> ProgressEvent[ApiGatewayModelProperties]:
        """
        Fetch resource information

        IAM permissions required:
          - apigateway:GET
        """
        raise NotImplementedError

    def delete(
        self,
        request: ResourceRequest[ApiGatewayModelProperties],
    ) -> ProgressEvent[ApiGatewayModelProperties]:
        """
        Delete a resource

        IAM permissions required:
          - apigateway:GET
          - apigateway:DELETE
        """
        model = request.desired_state
        apigw = request.aws_client_factory.apigateway
        try:
            apigw.delete_model(modelName=model["Name"], restApiId=model["RestApiId"])
        except apigw.exceptions.NotFoundException:
            # We are using try/except since at the moment
            # CFN doesn't properly resolve dependency between resources
            # so this resource could be deleted if parent resource was deleted first
            pass

        return ProgressEvent(
            status=OperationStatus.SUCCESS,
            resource_model=model,
            custom_context=request.custom_context,
        )

    def update(
        self,
        request: ResourceRequest[ApiGatewayModelProperties],
    ) -> ProgressEvent[ApiGatewayModelProperties]:
        """
        Update a resource

        IAM permissions required:
          - apigateway:PATCH
          - apigateway:GET
        """
        raise NotImplementedError
